<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="使用方式主要有3种使用方式: 1.修饰实例方法：作用于当前实例加锁 123public synchronized void method()&amp;#123;		&#x2F;&#x2F; 代码&amp;#125;  2.修饰静态方法：作用于当前类对象加锁 123public static synchronized void method()&amp;#123;		&#x2F;&#x2F; 代码&amp;#125;  3.修饰代码块：指定加锁对象，对给定对象加锁 12">
<meta property="og:type" content="article">
<meta property="og:title" content="synchronized">
<meta property="og:url" content="http://example.com/2022/03/16/synchronized/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="使用方式主要有3种使用方式: 1.修饰实例方法：作用于当前实例加锁 123public synchronized void method()&amp;#123;		&#x2F;&#x2F; 代码&amp;#125;  2.修饰静态方法：作用于当前类对象加锁 123public static synchronized void method()&amp;#123;		&#x2F;&#x2F; 代码&amp;#125;  3.修饰代码块：指定加锁对象，对给定对象加锁 12">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2022/03/16/synchronized/synchronized%E9%94%81%E5%AD%98%E5%82%A8%E7%BB%93%E6%9E%84.png">
<meta property="og:image" content="https://xiaomi-info.github.io/2020/03/24/synchronized/sync_1.png">
<meta property="article:published_time" content="2022-03-16T14:34:01.000Z">
<meta property="article:modified_time" content="2023-01-04T17:07:48.179Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="Java多线程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2022/03/16/synchronized/synchronized%E9%94%81%E5%AD%98%E5%82%A8%E7%BB%93%E6%9E%84.png">


<link rel="canonical" href="http://example.com/2022/03/16/synchronized/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2022/03/16/synchronized/","path":"2022/03/16/synchronized/","title":"synchronized"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>synchronized | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="nav-number">1.</span> <span class="nav-text">使用方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BA%95%E5%B1%82%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.</span> <span class="nav-text">底层实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java%E5%AF%B9%E8%B1%A1%E5%A4%B4"><span class="nav-number">2.1.</span> <span class="nav-text">Java对象头</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Monitor"><span class="nav-number">2.2.</span> <span class="nav-text">Monitor</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81%E6%B5%81%E8%BD%AC%E5%9C%A8Monitor%E4%B8%8A%E7%9A%84%E4%BD%93%E7%8E%B0"><span class="nav-number">2.2.1.</span> <span class="nav-text">线程状态流转在Monitor上的体现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%94%81%E5%8D%87%E7%BA%A7"><span class="nav-number">3.</span> <span class="nav-text">锁升级</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%81%8F%E5%90%91%E9%94%81"><span class="nav-number">3.1.</span> <span class="nav-text">偏向锁</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%81%8F%E5%90%91%E9%94%81%E7%9A%84%E5%8D%87%E7%BA%A7"><span class="nav-number">3.1.1.</span> <span class="nav-text">偏向锁的升级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%81%8F%E5%90%91%E9%94%81%E7%9A%84%E5%8F%96%E6%B6%88"><span class="nav-number">3.1.2.</span> <span class="nav-text">偏向锁的取消</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%98%E7%82%B9"><span class="nav-number">3.1.3.</span> <span class="nav-text">优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9"><span class="nav-number">3.1.4.</span> <span class="nav-text">缺点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81"><span class="nav-number">3.2.</span> <span class="nav-text">轻量级锁</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8A%A0%E9%94%81"><span class="nav-number">3.2.1.</span> <span class="nav-text">加锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E9%94%81"><span class="nav-number">3.2.2.</span> <span class="nav-text">解锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%98%E7%82%B9-1"><span class="nav-number">3.2.3.</span> <span class="nav-text">优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9-1"><span class="nav-number">3.2.4.</span> <span class="nav-text">缺点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8D%E9%87%8F%E7%BA%A7%E9%94%81"><span class="nav-number">3.3.</span> <span class="nav-text">重量级锁</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#monitor-%E7%AB%9E%E4%BA%89%E8%BF%87%E7%A8%8B"><span class="nav-number">3.3.1.</span> <span class="nav-text">monitor 竞争过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#monitor-%E9%87%8A%E6%94%BE"><span class="nav-number">3.3.2.</span> <span class="nav-text">monitor 释放</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2022/03/16/synchronized/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="synchronized | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          synchronized
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-16 22:34:01" itemprop="dateCreated datePublished" datetime="2022-03-16T22:34:01+08:00">2022-03-16</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-01-05 01:07:48" itemprop="dateModified" datetime="2023-01-05T01:07:48+08:00">2023-01-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">Java多线程</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="使用方式"><a href="#使用方式" class="headerlink" title="使用方式"></a>使用方式</h1><p>主要有3种使用方式:</p>
<p><strong>1.修饰实例方法：作用于当前实例加锁</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">method</span><span class="params">()</span>&#123;</span><br><span class="line">		<span class="comment">// 代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>2.修饰静态方法：作用于当前类对象加锁</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">method</span><span class="params">()</span>&#123;</span><br><span class="line">		<span class="comment">// 代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>3.修饰代码块：指定加锁对象，对给定对象加锁</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span>(<span class="built_in">this</span>)&#123;</span><br><span class="line">		<span class="comment">//代码                                  </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="底层实现"><a href="#底层实现" class="headerlink" title="底层实现"></a>底层实现</h1><p>synchronized的底层实现是完全依赖JVM虚拟机的,所以谈synchronized的底层实现，就不得不谈数据在JVM内存的存储：Java对象头，以及Monitor对象监视器。</p>
<h2 id="Java对象头"><a href="#Java对象头" class="headerlink" title="Java对象头"></a>Java对象头</h2><p>在JVM虚拟机中，对象在内存中的存储布局，可以分为三个区域:</p>
<ul>
<li>对象头(Header)</li>
<li>实例数据(Instance Data)</li>
<li>对齐填充(Padding)</li>
</ul>
<p><strong>Java对象头主要包括两部分数据：</strong></p>
<p><img src="/2022/03/16/synchronized/synchronized%E9%94%81%E5%AD%98%E5%82%A8%E7%BB%93%E6%9E%84.png"></p>
<p><strong>1)类型指针（Klass Pointer）</strong></p>
<p>是对象指向它的类元数据的指针，虚拟机通过这个指针来确定这个对象是哪个类的实例；</p>
<p><strong>2)标记字段(Mark Word)</strong></p>
<p>用于存储对象自身的运行时数据，如哈希码（HashCode）、GC分代年龄、锁状态标志、持有锁的线程、偏向线程 ID、偏向时间戳等等,它是实现轻量级锁和偏向锁的关键.</p>
<p>所以，很明显synchronized使用的锁对象是存储在Java对象头里的标记字段里。</p>
<p>64 位虚拟机 Mark Word 是 64bit 其结构如下：<br><img src="https://xiaomi-info.github.io/2020/03/24/synchronized/sync_1.png"></p>
<h2 id="Monitor"><a href="#Monitor" class="headerlink" title="Monitor"></a>Monitor</h2><p>monitor描述为对象监视器,可以类比为一个特殊的房间，这个房间中有一些被保护的数据，monitor保证每次只能有一个线程能进入这个房间进行访问被保护的数据，进入房间即为持有monitor，退出房间即为释放monitor。</p>
<p>使用syncrhoized加锁的同步代码块在字节码引擎中执行时，主要就是通过锁对象的monitor的取用(monitorenter)与释放(monitorexit)来实现的。（不过 syncrhoized 方法块不是使用到这两个字节码指令）</p>
<h3 id="线程状态流转在Monitor上的体现"><a href="#线程状态流转在Monitor上的体现" class="headerlink" title="线程状态流转在Monitor上的体现"></a>线程状态流转在Monitor上的体现</h3><p>当多个线程同时请求某个对象监视器时，对象监视器会设置几种状态用来区分请求的线程：</p>
<p>Contention List：所有请求锁的线程将被首先放置到该竞争队列<br>Entry List：Contention List中那些有资格成为候选人的线程被移到Entry List<br>Wait Set：那些调用wait方法被阻塞的线程被放置到Wait Set<br>OnDeck：任何时刻最多只能有一个线程正在竞争锁，该线程称为OnDeck<br>Owner：获得锁的线程称为Owner<br>!Owner：释放锁的线程</p>
<h1 id="锁升级"><a href="#锁升级" class="headerlink" title="锁升级"></a>锁升级</h1><p>在 JDK 6 中虚拟机团队对锁进行了重要改进，优化了其性能引入了 <strong>偏向锁、轻量级锁、适应性自旋、锁消除、锁粗化</strong>等实现，其中<strong>锁消除和锁粗化</strong>本文不做详细讨论其余内容我们将对其进行逐一探究。</p>
<p>锁的4中状态：无锁状态、偏向锁状态、轻量级锁状态、重量级锁状态（级别从低到高）</p>
<h2 id="偏向锁"><a href="#偏向锁" class="headerlink" title="偏向锁"></a>偏向锁</h2><blockquote>
<p>为什么要引入偏向锁？</p>
</blockquote>
<p>因为经过HotSpot的作者大量的研究发现，<strong>大多数时候是不存在锁竞争的</strong>，<strong>常常是一个线程多次获得同一个锁</strong>，因此如果每次都要竞争锁会增大很多没有必要付出的代价，为了降低获取锁的开销，才引入的偏向锁。</p>
<h3 id="偏向锁的升级"><a href="#偏向锁的升级" class="headerlink" title="偏向锁的升级"></a>偏向锁的升级</h3><p><strong>当线程1访问代码块并获取锁对象时，会在java对象头和栈帧中记录偏向的锁的threadID</strong>，因为<strong>偏向锁不会主动释放锁</strong>，因此以后线程1再次获取锁的时候，需要<strong>比较当前线程的threadID和Java对象头中的threadID是否一致</strong>，如果一致（还是线程1获取锁对象），则无需使用CAS来加锁、解锁；如果不一致（其他线程，如线程2要竞争锁对象，而偏向锁不会主动释放因此还是存储的线程1的threadID），那么<strong>需要查看Java对象头中记录的线程1是否存活</strong>，</p>
<ol>
<li><p><strong>如果没有存活，那么锁对象被重置为无锁状态</strong>，其它线程（线程2）可以竞争将其设置为偏向锁cas；</p>
</li>
<li><p><strong>如果存活，那么立刻查找该线程（线程1）的栈帧信息</strong>，</p>
<ul>
<li>如果还是需要继续持有这个锁对象，那么<strong>暂停当前线程1，撤销偏向锁，升级为轻量级锁</strong>，</li>
<li>如果线程 1 不再使用该锁对象，那么<strong>将锁对象状态设为无锁状态，重新偏向新的线程</strong>cas。</li>
</ul>
</li>
</ol>
<blockquote>
<p>偏向锁不会主动释放，只有被动撤销。</p>
</blockquote>
<h3 id="偏向锁的取消"><a href="#偏向锁的取消" class="headerlink" title="偏向锁的取消"></a>偏向锁的取消</h3><p>偏向锁是默认开启的，而且开始时间一般是比应用程序启动慢几秒，如果不想有这个延迟，那么可以使用-XX:BiasedLockingStartUpDelay&#x3D;0；</p>
<p>如果不想要偏向锁，那么可以通过-XX:-UseBiasedLocking &#x3D; false来设置；</p>
<h3 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h3><p>只有一个线程执行同步块时进一步提高性能，适用于一个线程反复获得同一锁的情况。偏向锁可以提高带有同步但无竞争的程序性能。</p>
<h3 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h3><p>如果存在竞争会带来额外的锁撤销操作。</p>
<h2 id="轻量级锁"><a href="#轻量级锁" class="headerlink" title="轻量级锁"></a>轻量级锁</h2><blockquote>
<p>为什么要引入轻量级锁？</p>
</blockquote>
<p>轻量级锁考虑的是<strong>竞争锁对象的线程不多</strong>，而且<strong>线程持有锁的时间也不长</strong>的情景。</p>
<p>因为<strong>阻塞线程需要CPU从用户态转到内核态，代价较大</strong>，如果刚刚阻塞不久这个锁就被释放了，那这个代价就有点得不偿失了，因此这个时候就<strong>干脆不阻塞这个线程，让它自旋这等待锁释放</strong>。</p>
<p>轻量级锁什么时候升级为重量级锁？</p>
<p>线程1获取轻量级锁时会<strong>先把锁对象的对象头MarkWord复制一份到线程1的栈帧中创建的用于存储锁记录的空间（称为DisplacedMarkWord）</strong>，然后<strong>使用CAS把对象头中的内容替换为线程1存储的锁记录（DisplacedMarkWord）的地址</strong>；</p>
<p>如果在线程1复制对象头的同时（在线程1CAS之前），线程2也准备获取锁，复制了对象头到线程2的锁记录空间中，但是在<strong>线程2CAS的时候，发现线程1已经把对象头换了，线程2的CAS失败，那么线程2就尝试使用自旋锁来等待线程1释放锁</strong>。</p>
<h3 id="加锁"><a href="#加锁" class="headerlink" title="加锁"></a>加锁</h3><p><strong>多个线程竞争偏向锁导致偏向锁升级为轻量级锁。</strong></p>
<ol>
<li>JVM 在当前线程的栈帧中创建 Lock Reocrd，并将对象头中的 Mark Word 复制到 Lock Reocrd 中。（Displaced Mark Word）</li>
<li>线程尝试使用 CAS 将对象头中的 Mark Word 替换为指向 Lock Reocrd 的指针。如果成功则获得锁，如果失败则先检查对象的 Mark Word 是否指向当前线程的栈帧，如果是则说明已经获取锁，否则说明其它线程竞争锁则膨胀为重量级锁。</li>
</ol>
<h3 id="解锁"><a href="#解锁" class="headerlink" title="解锁"></a>解锁</h3><ol>
<li>使用 CAS 操作将 Mark Word 还原</li>
<li>如果第 1 步执行成功则释放完成</li>
<li>如果第 1 步执行失败则膨胀为重量级锁（执行失败说明存在竞争）。<del>存疑</del></li>
</ol>
<h3 id="优点-1"><a href="#优点-1" class="headerlink" title="优点"></a>优点</h3><p>其性能提升的依据是对于绝大部分的锁在整个生命周期内都是不会存在竞争。在多线程交替执行同步块的情况下，可以避免重量级锁引起的性能消耗。</p>
<h3 id="缺点-1"><a href="#缺点-1" class="headerlink" title="缺点"></a>缺点</h3><p>在有多线程竞争的情况下轻量级锁增加了额外开销。</p>
<p>但是如果自旋的时间太长也不行，因为自旋是要消耗CPU的，因此自旋的次数是有限制的，比如10次或者100次，如果自旋次数到了线程1还没有释放锁，或者线程1还在执行，线程2还在自旋等待，这时又有一个线程3过来竞争这个锁对象，那么这个时候轻量级锁就会膨胀为重量级锁。这个时候又有了自适应自旋的概念。</p>
<h2 id="重量级锁"><a href="#重量级锁" class="headerlink" title="重量级锁"></a>重量级锁</h2><p><strong>重量级锁把除了拥有锁的线程都阻塞，防止CPU空转</strong>。</p>
<p>注意：为了避免无用的自旋，<strong>轻量级锁一旦膨胀为重量级锁就不会再降级为轻量级锁了</strong>；</p>
<p><strong>偏向锁升级为轻量级锁也不能再降级为偏向锁</strong>。</p>
<p>一句话就是锁可以升级不可以降级，但是偏向锁状态可以被重置为无锁状态。</p>
<blockquote>
<p>但是一旦释放重量级锁，就重新回到上面的流程中了。</p>
</blockquote>
<p>在重量级锁中没有竞争到锁的对象会 park 被挂起，退出同步块时 unpark 唤醒后续线程。唤醒操作涉及到操作系统调度会有额外的开销。</p>
<p><code>ObjectMonitor</code> 中包含一个同步队列（由 <code>_cxq</code> 和 <code>_EntryList</code> 组成）一个等待队列（ <code>_WaitSet</code> ）。</p>
<ul>
<li>被<code>notify</code>或 <code>notifyAll</code> 唤醒时根据 <code>policy</code> 策略选择加入的队列（policy 默认为 0）</li>
<li>退出同步块时根据 <code>QMode</code> 策略来唤醒下一个线程（QMode 默认为 0）</li>
</ul>
<p>这里稍微提及一下<strong>管程</strong>这个概念。synchronized 关键字及 <code>wait</code>、<code>notify</code>、<code>notifyAll</code> 这三个方法都是管程的组成部分。可以说管程就是一把解决并发问题的万能钥匙。有两大核心问题管程都是能够解决的：</p>
<ul>
<li><strong>互斥</strong>：即同一时刻只允许一个线程访问共享资源；</li>
<li><strong>同步</strong>：即线程之间如何通信、协作。</li>
</ul>
<p><code>synchronized</code> 的 <code>monitor</code>锁机制和 JDK 并发包中的 <code>AQS</code> 是很相似的，只不过 <code>AQS</code> 中是一个同步队列多个等待队列。熟悉 <code>AQS</code> 的同学可以拿来做个对比。</p>
<blockquote>
<p>在 HotSpot 中 monitor 是由 ObjectMonitor 实现的。</p>
</blockquote>
<h3 id="monitor-竞争过程"><a href="#monitor-竞争过程" class="headerlink" title="monitor 竞争过程"></a>monitor 竞争过程</h3><ol>
<li>通过 CAS 尝试把 monitor 的 owner 字段设置为当前线程。</li>
<li>如果设置之前的 owner 指向当前线程，说明当前线程再次进入 monitor，即重入锁执行 recursions ++ , 记录重入的次数。</li>
<li>如果当前线程是第一次进入该 monitor, 设置 recursions 为 1,_owner 为当前线程，该线程成功获得锁并返回。</li>
<li>如果获取锁失败，则等待锁的释放。</li>
</ol>
<p>执行 <code>monitorenter</code> 指令时会调用cpp编写的代码。</p>
<h3 id="monitor-释放"><a href="#monitor-释放" class="headerlink" title="monitor 释放"></a>monitor 释放</h3><p>当某个持有锁的线程执行完同步代码块时，会释放锁并 <code>unpark</code> 后续线程（由于篇幅只保留重要代码）。</p>
<blockquote>
<p>参考<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/tongdanping/article/details/79647337">https://blog.csdn.net/tongdanping/article/details/79647337</a><br><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903913120874510">https://juejin.cn/post/6844903913120874510</a><br><a target="_blank" rel="noopener" href="https://juejin.cn/post/6936067917255540767">https://juejin.cn/post/6936067917255540767</a><br><a target="_blank" rel="noopener" href="https://xiaomi-info.github.io/2020/03/24/synchronized/">https://xiaomi-info.github.io/2020/03/24/synchronized/</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"># Java多线程</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/03/16/LVS/" rel="prev" title="LVS">
                  <i class="fa fa-chevron-left"></i> LVS
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/03/16/select%E3%80%81poll%E3%80%81epoll/" rel="next" title="《Unix网络编程》—— echo server的bio、select、poll、epoll多种实现">
                  《Unix网络编程》—— echo server的bio、select、poll、epoll多种实现 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
